﻿@page "/login-callback"
@layout EmptyLayout

@using System.Web
@inject NavigationManager NavigationManager
@inject IConfiguration configure
@inject HttpClient HttpClient
@inject IJSRuntime JSRuntime

@code {

    public string Code { get; set; }
    public string SelfUrl => configure.GetSection("App")["SelfUrl"];

    public class TokenResult
    {
        public string access_token { get; set; }
    }

    protected async override Task OnInitializedAsync()
    {
        var query = HttpUtility.ParseQueryString(new Uri(NavigationManager.Uri).Query);
        Code = query["code"];
        if (string.IsNullOrEmpty(Code))
            return;
        var tokenResult = await GetTokenAsync();
        if (!string.IsNullOrEmpty(tokenResult.access_token))
        {
            HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenResult.access_token);
            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "Authorization", "Bearer " + tokenResult.access_token);
            //await sessionStorage.SetItemAsync("Authorization", "Bearer " + tokenResult.access_token);
            var userinfo = await GetUserInfo();
            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "userinfo", JsonSerializer.Serialize(userinfo));
        }
        //await JSRuntime.InvokeVoidAsync("close");
        NavigationManager.NavigateTo("/");
    }


    public async Task<TokenResult> GetTokenAsync()
    {
        //var dto = new
        //{
        //    grant_type = "authorization_code",
        //    code = Code,
        //    client_id = "Blog_Blazor",
        //    client_secret = "1q2w3e*",
        //    redirect_uri = $"{SelfUrl}/authentication/login-callback"
        //};
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("grant_type", "authorization_code");
        para.Add("code", Code);
        para.Add("client_id", "Blog_Blazor");
        para.Add("client_secret", "1q2w3e*");
        para.Add("redirect_uri", $"{SelfUrl}/login-callback");
        string url = "/connect/token";
        FormUrlEncodedContent content = new FormUrlEncodedContent(para);
        var result = await HttpClient.PostAsync(url, content);
        if ((int)result.StatusCode == 200)
            return await result.Content.ReadFromJsonAsync<TokenResult>();
        else
            return new TokenResult();
    }

    //获取用户数据
    public async Task<UserInfoDto> GetUserInfo()
    {
        try
        {
            var res = await HttpClient.GetFromJsonAsync<UserInfoDto>("/api/blog/my-account/user-info");
            return res;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return new UserInfoDto();
        }
    }
}
